import express from "express";
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";

const app = express();
app.use(express.json());

app.post('/mcp', async (req, res,) => {
    // In stateless mode, create a new instance of transport and server for each request
    // to ensure complete isolation. A single instance would cause request ID collisions
    // when multiple clients connect concurrently.

    try {
        const server = new McpServer({
            name: "example-server",
            version: "1.0.0"
        });

        // ... set up server resources, tools, and prompts ...
        server.resource(
            "echo",
            new ResourceTemplate("echo://{message}", { list: undefined }),
            async (uri, { message }) => ({
                contents: [{
                    uri: uri.href,
                    text: `Resource echo: ${message}`
                }]
            })
        );

        server.tool("student_query",
            { age: z.number(), email: z.string() },
            async ({ }) => {
                return {
                    content: [
                        {
                            type: "text",
                            text: `查询结果为json格式，数据如下：[{ "id": 11, "name": "hl", "age": 18, "email": "fedhong.com", "created_at": "2025-06-04T02:00:53.000Z", "updated_at": "2025-06-04T02:00:53.000Z" }, { "id": 10, "name": "王十二", "age": 33, "email": "wangshier@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 9, "name": "郑十一", "age": 26, "email": "zhengshiyi@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 8, "name": "吴十", "age": 29, "email": "wushi@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 7, "name": "周九", "age": 31, "email": "zhoujiu@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 6, "name": "孙八", "age": 27, "email": "sunba@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 5, "name": "钱七", "age": 35, "email": "qianqi@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 4, "name": "赵六", "age": 22, "email": "zhaoliu@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 3, "name": "王五", "age": 28, "email": "wangwu@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }, { "id": 2, "name": "李四", "age": 30, "email": "lisi@example.com", "created_at": "2025-06-03T14:58:52.000Z", "updated_at": "2025-06-03T14:58:52.000Z" }]`
                        }
                    ]
                }
            }
        );

        server.tool(
            "echo",
            { message: z.string() },
            async ({ message }) => ({
                content: [{ type: "text", text: `Tool echo: ${message}` }]
            })
        );

        server.prompt(
            "echo",
            { message: z.string() },
            ({ message }) => ({
                messages: [{
                    role: "user",
                    content: {
                        type: "text",
                        text: `Please process this message: ${message}`
                    }
                }]
            })
        );

        const transport = new StreamableHTTPServerTransport({
            sessionIdGenerator: undefined,
        });
        res.on('close', () => {
            console.log('Request closed');
            transport.close();
            server.close();
        });
        await server.connect(transport);
        await transport.handleRequest(req, res, req.body);
    } catch (error) {
        console.error('Error handling MCP request:', error);
        if (!res.headersSent) {
            res.status(500).json({
                jsonrpc: '2.0',
                error: {
                    code: -32603,
                    message: 'Internal server error',
                },
                id: null,
            });
        }
    }
});

app.get('/mcp', async (req, res) => {
    console.log('Received GET MCP request');
    res.writeHead(405).end(JSON.stringify({
        jsonrpc: "2.0",
        error: {
            code: -32000,
            message: "Method not allowed."
        },
        id: null
    }));
});

app.delete('/mcp', async (req, res) => {
    console.log('Received DELETE MCP request');
    res.writeHead(405).end(JSON.stringify({
        jsonrpc: "2.0",
        error: {
            code: -32000,
            message: "Method not allowed."
        },
        id: null
    }));
});

app.get('/test', async (req, res) => {
    console.log('Received GET test request');
    res.writeHead(200).end(JSON.stringify({
        jsonrpc: "2.0",
        error: {
            code: -32000,
            message: "Method not allowed."
        },
        id: null
    }));
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`);
});
